package config

import (
	"fmt"
	"os"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var Conf = new(LibraryConfig)

type MysqlConfig struct {
	Host     string `mapstructure:"host"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	DB       string `mapstructure:"db"`
	Port     int    `mapstructure:"port"`
}
type LogConfig struct {
	Level      string `mapstructure:"level"`
	MaxSize    int    `mapstructure:"max_size"`
	MaxBackups int    `mapstructure:"max_backups"`
	MaxAge     int    `mapstructure:"max_age"`
}

type Server struct {
	Address            string `mapstructure:"address"`
	TokenSecret        string `mapstructure:"token_secret"`
	TokenExpiredSecond int64  `mapstructure:"token_expired_second"`
}

type LibraryConfig struct {
	Debug         bool   `mapstructure:"debug"`
	LazyImg       int    `mapstructure:"lazy_img"`
	Root          string // 程序执行根目录
	Name          string `mapstructure:"name"`
	LoginUsername string `mapstructure:"login_username"` // 后台登陆用户名
	LoginPassword string `mapstructure:"login_password`  // 后台登陆密码
	PageSize      string `mapstructure:"page_size"`      // 默认分页数量

	*Server      `mapstructure:"server"`
	*LogConfig   `mapstructure:"log"`
	*MysqlConfig `mapstructure:"mysql"`
}

func init() {
	var err error
	v := viper.New()
	v.SetConfigName("config")
	v.SetConfigType("toml")
	v.AddConfigPath(".")

	v.SetDefault("debug", false)
	v.SetDefault("lazy_img", 0)
	v.SetDefault("name", "note")
	v.SetDefault("page_size", "12")
	v.SetDefault("login_username", "admin")
	v.SetDefault("login_password", "admin")
	v.SetDefault("page_size", "12")
	v.SetDefault("server", map[string]interface{}{"address": ":50000", "token_secret": "UfSCpUn33s~gu+NeR9$3FDq%$ktWa77Av0T&f", "token_expired_second": 96000})
	v.SetDefault("log", map[string]interface{}{"level": "debug", "max_size": 10, "max_backups": 50, "max_age": 30})
	v.SetDefault("mysql", map[string]interface{}{"host": "localhost", "user": "root", "password": "root", "db": "note", "port": 3306, "max_open_conns": 100, "max_idle_conns": 20})

	if err = v.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			v.SafeWriteConfig()
		}
	}

	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed")
		err = v.Unmarshal(&Conf)
		if err != nil {
			panic(fmt.Errorf("配置文件修改后报错:%v", err))
		}
	})
	if err = v.Unmarshal(&Conf); err != nil {
		panic(fmt.Errorf("unmarshal data to Conf failed,err:%v", err))
	}

	Conf.Root, _ = os.Getwd()
}
